import { computed, Ref, ref } from "vue";
import { useCommon } from "./useCommon";
import { useCursorManager } from "./useCursorManager";
import { Debounce } from "@/utils/common";
import { useTrigger } from "./useTrigger";
import { useChat } from "@/store/modules/chat";
import { ChatType, MessageType } from "@/types/chat";
import { ElMessage } from "element-plus";
import { MessageStrategyMap } from "@/tactics/message";
import { HandelFileUploadProgress } from "@/utils/file";
import { useCache } from "@/store/modules/cache";

export function useInput(messageInputDom: Ref) {
  const { RemoveTag } = useCommon();
  const chat = useChat();
  const cache = useCache();
  let InputVal = ref("");
  let Ait = ref(false);
  let AitVal = ref("");
  let ActiveQuotationId = ref("");
  let IsDisabled = ref(true);
  const DisabledSend = computed(() => {
    const BasicContentText = RemoveTag(InputVal.value);
    return BasicContentText.length === 0 || BasicContentText.replace(/&nbsp;/g, " ").trim().length === 0;
  });

  let FilterMemberList = computed(() => {
    if (!Ait.value) return [];
    let members = cache.GroupMemberCache.get(chat.ChatObject?.id!);
    if (!members) return [];
    return members?.filter((item) => item.name.includes(AitVal.value));
  });
  const { Focus, GetCursorSelectionRange, UpdateSelectionRange } = useCursorManager();
  const { GetEditor, GetMessageContentType } = useCommon();
  const { HandelTrigger } = useTrigger(Ait, AitVal);

  // 提取@的用户id
  function ExtractAtUserIds(content: string): number[] {
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = content;
    const BasicContentText = tempDiv.textContent || "";
    const mentionRegex = /@([^\s@]+)/g;
    const matchedUsernames = [...BasicContentText.matchAll(mentionRegex)].map((match) => match[1]);
    const userMap = new Map<string, number>();
    let members = cache.GroupMemberCache.get(chat.ChatObject?.id!);
    if (!members) return [];
    members.forEach((member) => {
      userMap.set(member.name, member.id);
    });

    const userIdSet = new Set<number>();
    matchedUsernames.forEach((name) => {
      const id = userMap.get(name);
      if (id !== undefined) {
        userIdSet.add(id);
      }
    });
    return [...userIdSet];
  }

  // 处理输入
  const HandelInput = Debounce(async (e: Event) => {
    const inputElement = e.target as HTMLInputElement;
    InputVal.value = inputElement.innerHTML;
    const { range, selection } = GetEditor()!;
    if (!range || !selection) return;
    const curNode = range.endContainer;
    console.log(curNode.textContent, curNode.nodeName);
    if (!curNode || !curNode.textContent || curNode.nodeName !== "#text") {
      ResetState();
      return;
    }
    const cursorPosition = selection.focusOffset;
    const text = curNode.textContent!;
    console.log(cursorPosition, text);

    // 只有是群聊才能@
    if (chat.ChatObject!.chatType === ChatType.group && text.includes("@")) {
      await HandelTrigger(text, cursorPosition, {
        range,
        selection,
        keyword: "",
      });
    }
  });

  // 发送消息
  async function Send(e: Event) {
    e.preventDefault();
    if (DisabledSend.value) return;
    // todo:消息引用去除显示头像
    const imgCount = messageInputDom.value.querySelectorAll("img").length;
    if (imgCount > 4) {
      ElMessage.warning("超出上传文件最大数");
      return;
    }
    const messageType = GetMessageContentType(messageInputDom);
    const strategy = MessageStrategyMap[messageType];
    const result = strategy.getMsg({
      content: InputVal.value,
      quotationId: ActiveQuotationId.value,
      aitIds: ExtractAtUserIds(InputVal.value),
      messageInputDom,
    });
    if (!result) {
      console.log("input send 消息发送失败");
      return;
    }
    const { message, file } = result;
    console.log("这是准备发送的消息", message);
    ResetInput();
    switch (message.messageType) {
      case MessageType.text:
        window.electronApi.sendMessage(message);
        break;
      default:
        await HandelFileUploadProgress(message, file!);
        break;
    }
  }

  // 重置所有状态
  function ResetState() {
    ActiveQuotationId.value = "";
    AitVal.value = "";
    Ait.value = false;
  }

  // 重置
  function ResetInput() {
    InputVal.value = "";
    messageInputDom.value.innerHTML = "";
    ActiveQuotationId.value = "";
  }

  return {
    HandelInput,
    InputVal,
    Focus,
    Ait,
    IsDisabled,
    ActiveQuotationId,
    FilterMemberList,
    GetCursorSelectionRange,
    Send,
    DisabledSend,
    updateSelectionRange: () => UpdateSelectionRange(GetEditor()),
  };
}
